import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ServerMetric } from '../entities/server-metric.entity';

@Injectable()
export class AnalyticsService {
  constructor(
    @InjectRepository(ServerMetric)
    private serverMetricRepo: Repository<ServerMetric>,
  ) {}

  async getCpuTrend(servers: string[], startTime: Date, endTime: Date) {
    return this.serverMetricRepo
      .createQueryBuilder('metric')
      .innerJoinAndSelect('metric.server', 'server')
      .where('metric.collectedAt BETWEEN :start AND :end', {
        start: startTime,
        end: endTime,
      })
      .andWhere('server.serverName IN (:...names)', { names: servers })
      .orderBy('metric.collectedAt', 'ASC')
      .getMany();
  }
}